<template>
  <el-form ref="staffNumLoginForm" :model="staffNumLoginForm" :rules="staffNumLoginRules" auto-complete="on">
    <el-form-item prop="staffNum">
      <el-input ref="staffNum" v-model.trim="staffNumLoginForm.staffNum" placeholder="工号" name="staffNum" type="text" auto-complete="on" />
    </el-form-item>

    <el-form-item prop="password">
      <el-input :key="passwordType" ref="password" v-model.trim="staffNumLoginForm.password" :type="passwordType" placeholder="密码" name="password" auto-complete="on" @keyup.enter.native="handleLogin" />
    </el-form-item>

    <el-button :loading="loading" type="primary" style="width: 100%; margin: 10px 0 20px" @click.native.prevent="handleLogin"> 登 录 </el-button>
  </el-form>
</template>

<script>
export default {
  name: 'LogByWorkNumber',
  props: {
    redirect: {
      type: String,
      default: '/'
    }
  },
  data() {
    return {
      loading: false,
      passwordType: 'password',
      // 工号登录下表单
      staffNumLoginForm: {
        staffNum: '',
        password: ''
      },
      // 表单验证
      staffNumLoginRules: {
        staffNum: [{ required: true, trigger: 'blur', message: '请输入工号' }],
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }]
      }
    }
  },
  methods: {
    // 登录事件
    handleLogin() {
      this.$refs.staffNumLoginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/loginByStaffNum', this.staffNumLoginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>
